package com.dpad.crmclientapp.android.modules.newapp.ui.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v7.app.AlertDialog
import android.text.TextUtils
import android.view.View
import android.webkit.*
import android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
import android.widget.Toast
import com.dpad.telematicsclientapp.android.R
import com.dpad.telematicsclientapp.mvp.event.BusProvider
import com.dpad.telematicsclientapp.netlibrary.AppConstants
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyFragment
import com.dpad.telematicsclientapp.netlibrary.http.ApiConstants
import com.dpad.telematicsclientapp.netlibrary.http.NetInstance
import com.dpad.telematicsclientapp.netlibrary.net.NetErrorCode
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.PayInfo
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.PayInfoback
import com.dpad.telematicsclientapp.presenter.NullPresenter
import com.dpad.telematicsclientapp.ui.HomeActivity
import com.dpad.telematicsclientapp.util.DataStatisticsUtils
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.ViewUtils
import com.dpad.telematicsclientapp.util.utils.*
import com.dpad.telematicsclientapp.weiget.BasicDialog
import com.socks.library.KLog
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_t_mall.*
import rx.subscriptions.CompositeSubscription
import java.util.*

/**
 * ================================================
 * 作    者：wenbody
 * 版    本：1.0
 * 创建日期：2019/12/24 11:31
 * 修订历史：
 * ================================================
 */
class MallFragment : BaseCopyFragment<NullPresenter>() {

    private var url: String? = null
    private var needFinish = false
    private var goPay = false //跳转到微信
    private var gotoWxUrl = "" //跳转到微信后调用的的url(订单url)
    private var platformapiUrl: String? = null//支付宝记录的url
    var isHome = true //是否是首页

    private lateinit var cityCode: String
    private lateinit var lng: String
    private lateinit var lat: String
    private lateinit var phone: String
    private lateinit var brandCode: String
    private lateinit var visitor: String
    var activity: HomeActivity? = null


    var needLoadData = false

    private var webViewCallBack: WebViewCallBack? = null
    private  lateinit var api: IWXAPI
    private  lateinit var req: PayReq
    @RequiresApi(Build.VERSION_CODES.KITKAT)
    @SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface", "JavascriptInterface")
    override fun initPageData() {
        ViewUtils.setStatusView(context, status_view)
        t_mall_webview.setBackgroundColor(resources.getColor(R.color.color_tmall)) // 设置背景色
//        t_mall_webview.pauseTimers()
        cityCode = PreferenceUtils.getInstance(context).getString("cityCode")
        lng = PreferenceUtils.getInstance(context).getString("longitude")
        lat = PreferenceUtils.getInstance(context).getString("latitude")
        visitor = if (MainApplicaton.userVehType == "0") "1" else "0";
        phone = MainApplicaton.LOGINRESULTVO.userName
        brandCode = AppConstants.BRANDCODE
        activity = context as HomeActivity?
        val loginName = if (MainApplicaton.LOGINRESULTVO.nickName == null) "" else MainApplicaton.LOGINRESULTVO.nickName
        url = ApiConstants.getAppTmallUrl() + MainApplicaton.LOGINRESULTVO.token +
                "&vin=" + MainApplicaton.vin +
                "&userId=" + MainApplicaton.LOGINRESULTVO.userId +
                "&cityCode=" + cityCode +
                "&lng=" + lng +
                "&lat=" + lat +
                "&phone=" + phone +
                "&brandCode=" + brandCode +
                "&userName=" + loginName +
                "&visitor=" + visitor +
                "&loginName=" + MainApplicaton.LOGINRESULTVO.userName
//        url="https://ntsp.dpca.com.cn/nev_tmall/#/reviewed"
        KLog.e("h5地址", url)
        gotoWxUrl = url as String

        if (!TextUtils.isEmpty(url)) {
            t_mall_webview.loadUrl(url)
            t_mall_webview.requestFocus()
        }
        t_mall_webview.setDownloadListener(object : DownloadListener {
            override fun onDownloadStart(url: String?, userAgent: String?, contentDisposition: String?, mimetype: String?, contentLength: Long) {
                KLog.e("下载地址", url.toString())
            }

        })

        t_mall_webview.webViewClient = object : WebViewClient() {

            override fun onPageFinished(view: WebView, url: String) {
                KLog.e("onPageFinished地址", url);
                addDataByUrl(url);
                if("https://ntsp.dpca.com.cn/preprod/nev_tmall/#/".equals(url)||url.indexOf("https://ntsp.dpca.com.cn/preprod/nev_tmall/#/?token=")!=-1){
                    activity?.changeBottomVisible(true,url.toString());
                }else if("https://ntsp.dpca.com.cn/nev_tmall/#/".equals(url)||url.indexOf("https://ntsp.dpca.com.cn/nev_tmall/#/?token=")!=-1){
                    activity?.changeBottomVisible(true,url.toString());
                }else{activity?.changeBottomVisible(false,url.toString());}
                val ifcontains = url.contains("nev_tmall/#/paySuccess")
                if(ifcontains){
                    postJs();
                }
                super.onPageFinished(view, url)
            }

            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                KLog.e("shouldOverrideUrlLoading地址", url)
                // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                if (!url.contains("http")) {
                    if (url.startsWith("weixin://wap/pay?")) {
                        val intent = Intent()
                        intent.action = Intent.ACTION_VIEW
                        intent.data = Uri.parse(url)
                        startActivity(intent)
                        goPay = true
                        return true
                    } else if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        assert(activity != null)
                        platformapiUrl = url
                        try {
                            context.startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)))
                        } catch (e: Exception) {
                            AlertDialog.Builder(context)
                                    .setMessage("未检测到支付宝客户端，请安装后重试。")
                                    .setPositiveButton("立即安装") { dialog, which ->
                                        val alipayUrl = Uri.parse("https://d.alipay.com")
                                        context.startActivity(Intent("android.intent.action.VIEW", alipayUrl))
                                    }.setNegativeButton("取消", null).show()
                        }
                        goPay = true
                    } else if (url.startsWith("https://mclient.alipay.com/h5Continue.htm?")) {
                        assert(activity != null)
                        try {
                            context.startActivity(Intent("android.intent.action.VIEW", Uri.parse(url)))
                        } catch (e: Exception) {
                            AlertDialog.Builder(context)
                                    .setMessage("未检测到支付宝客户端，请安装后重试。")
                                    .setPositiveButton("立即安装") { dialog, which ->
                                        val alipayUrl = Uri.parse("https://d.alipay.com")
                                        context.startActivity(Intent("android.intent.action.VIEW", alipayUrl))
                                    }.setNegativeButton("取消", null).show()
                        }
                        goPay = true
                    }
                    return true
                } else {
                    val extraHeaders: MutableMap<String, String> = HashMap()
                    extraHeaders["Referer"] = "https://ntsp.dpca.com.cn"
                    view.loadUrl(url, extraHeaders)
//                    view.loadUrl(url)
                }
                return true
            }
        }

        t_mall_webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(webView: WebView, i: Int) {
                if (pb_webview != null) {
                    if (i == 100) {
                        pb_webview.visibility = View.GONE
                    } else {
                        pb_webview.visibility = View.VISIBLE
                        pb_webview.progress = i
                    }
                }
                super.onProgressChanged(webView, i)
            }

            override fun onGeolocationPermissionsShowPrompt(origin: String?, callback: GeolocationPermissions.Callback?) {
                super.onGeolocationPermissionsShowPrompt(origin, callback)
                callback?.invoke(origin, true, false)
            }


            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                DialogUtil.showBasicDialog(activity, "", message, "确定", object : BasicDialog.OnCloseListener {
                    override fun onClose(dialog: Dialog?, confirm: Boolean) {
                        if (confirm) {
                            result?.confirm()
                            dialog?.dismiss()
                        } else {
                            result?.cancel()
                        }
                    }

                })
                return true
            }

            override fun onJsPrompt(view: WebView?, url: String?, message: String?, defaultValue: String?, result: JsPromptResult?): Boolean {
                DialogUtil.showBasicDialog(activity, "", message, object : BasicDialog.OnCloseListener {
                    override fun onClose(dialog: Dialog?, confirm: Boolean) {
                        if (confirm) {
                            result?.confirm()
                            dialog?.dismiss()
                        } else {
                            result?.cancel()
                        }
                    }

                })
                return true
            }

            override fun onJsConfirm(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                DialogUtil.showBasicDialog(activity, "", message, "确定", object : BasicDialog.OnCloseListener {
                    override fun onClose(dialog: Dialog?, confirm: Boolean) {
                        if (confirm) {
                            result?.confirm()
                            dialog?.dismiss()
                        } else {
                            result?.cancel()
                        }
                    }

                })
                return true
            }
        }
        val settings: WebSettings = t_mall_webview.settings
        settings.builtInZoomControls = false // 显示缩放按钮(wap网页不支持)
        settings.useWideViewPort = false // 支持双击缩放(wap网页不支持)
        settings.javaScriptEnabled = true // 支持js功能
        settings.loadWithOverviewMode = false //缩放到屏幕大小
        settings.blockNetworkImage = false //解决图片不显示
        settings.loadsImagesAutomatically = true //支持自动加载图片
        settings.defaultTextEncodingName = "utf-8"//设置编码格式
        settings.domStorageEnabled = false
        settings.setAppCacheEnabled(false)
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        settings.setGeolocationEnabled(true)


        settings.javaScriptCanOpenWindowsAutomatically = true
        //混合开发时候(http和https),api23之后需要手动打开
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.mixedContentMode = MIXED_CONTENT_ALWAYS_ALLOW
        }


        webViewCallBack = activity?.let { WebViewCallBack(it) }

        t_mall_webview.addJavascriptInterface(webViewCallBack, "android")

        BusProvider.getBus()
                .toFlowable(UserLoginStateChangeEvent::class.java)
                .observeOn(AndroidSchedulers.mainThread()) //观察的对象
                .subscribe { t ->
                    if (t != null) {
                        KLog.e("Rxbus", "接收到了数据")
                        needLoadData = true
                    }
                }
    }

    override fun useEventBus(): Boolean {
        return true
    }

    override fun getLayout(): Int {
        return R.layout.fragment_t_mall
    }

    override fun newPresenter(subscriptions: CompositeSubscription?): NullPresenter? {
        return null
    }



    /**
     * 关闭当前页面
     */
    private fun closeActivity() {
        try {
            if (context != null) {
                context.finish()
            }
        } catch (e: java.lang.Exception) {
        }
    }

    override fun onResume() {
        super.onResume()

        KLog.e("onResume", "onResume")
       // postJs();
//        if (goPay) {
//            postJs()
//            goPay=false
//        }
    }
    /**
     * 调用js的方法
     */
    private fun postJs() {
        if(t_mall_webview!=null){
            t_mall_webview.loadUrl("javascript:getOrderStatus()");
        }
    }
    override fun visiableLoadData() {


        /**
         * 重新登录或者切换爱车需要刷新网址
         */
        if (needLoadData) {
            cityCode = PreferenceUtils.getInstance(context).getString("cityCode")
            lng = PreferenceUtils.getInstance(context).getString("longitude")
            lat = PreferenceUtils.getInstance(context).getString("latitude")
            phone = MainApplicaton.LOGINRESULTVO.userName
            brandCode = AppConstants.BRANDCODE

            val loginName = if (MainApplicaton.LOGINRESULTVO.nickName == null) "" else MainApplicaton.LOGINRESULTVO.nickName
            url = ApiConstants.getAppTmallUrl() + MainApplicaton.LOGINRESULTVO.token +
                    "&vin=" + MainApplicaton.vin +
                    "&userId=" + MainApplicaton.LOGINRESULTVO.userId +
                    "&cityCode=" + cityCode +
                    "&lng=" + lng +
                    "&lat=" + lat +
                    "&phone=" + phone +
                    "&brandCode=" + brandCode +
                    "&userName=" + loginName +
                    "&loginName=" + MainApplicaton.LOGINRESULTVO.userName
//            url="https://ntsp.dpca.com.cn/nev_tmall/#/reviewed"
            if (!TextUtils.isEmpty(url) && (MainApplicaton.sIsLogin)) {
                KLog.e("开始加载", url)
                t_mall_webview.clearCache(true)
                t_mall_webview.clearHistory()
                t_mall_webview.loadUrl(url)
                t_mall_webview.reload()
                needLoadData = false
            }
        }

    }



    inner class WebViewCallBack(mActivity: HomeActivity) {
        private var activity: HomeActivity? = null
        var isHome = true //是否是首页

        init {
            this.activity = mActivity
        }

        @JavascriptInterface
        fun show(show: Boolean) {
            isHome = show
            KLog.e("底部tab可见状态", show.toString())
            UIUtils.runInMainThread {
                //activity?.changeBottomVisible(show)
            }
            if (show) {
//                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE89.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            }
        }

        @JavascriptInterface
        fun invalid() {
            KLog.e("token过期", "token过期")
            NetErrorCode.detailToken()
            activity?.finish()
        }
        @JavascriptInterface
        fun pay(outTradeNo: String,subMchId: String) {
            KLog.e("JS 回调支付", outTradeNo+"回调支付"+subMchId)
            getPayData(outTradeNo,subMchId)
        }
    }

    fun backPress(): Boolean {
//        if (t_mall_webview.canGoBack()) {
//            t_mall_webview.goBack()
//            return false
//        } else {
        return true
//        }
    }

    override fun isTFragment(): Boolean {
        return true
    }

    override fun getPageTitle(): String {
        return TitleToCode.TYPE89.title
    }

    fun getPayData(outTradeNo: String,subMchId: String){
        val sortedMap: SortedMap<String, Any> = TreeMap()
        sortedMap["outTradeNo"] = outTradeNo
        sortedMap["subMchId"] = subMchId
        NetInstance.getEventsService().getwxpay(ParameterUtils.getHeaser(sortedMap), ParameterUtils.getJsonBody(sortedMap)).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(object : Observer<PayInfoback> {
            override fun onSubscribe(d: Disposable) {}
            override fun onNext(entity: PayInfoback) {
                KLog.e("PayInfobackPayInfobackPayInfobackPayInfoback!!!!@@@@code", entity.code)
                KLog.e("PayInfobackPayInfobackPayInfobackPayInfoback!!!!@@@@prepayid", entity.result.prepayid)
                if(entity.code=="0000"){
                    weixinPay(entity.result)
                }
            }
            override fun onError(e: Throwable) {}
            override fun onComplete() {}
        })
    }

    fun weixinPay(payInfo: PayInfo){
        MainApplicaton.APP_ID = payInfo.getAppid()
        Paywx(payInfo)
    }

    fun Paywx(payInfo: PayInfo) {
        if (judgeCanGo(payInfo.appid)) {
            genPayReq(payInfo)
            if (api != null) {
                api.registerApp(payInfo.appid)
                val b: Boolean = api.sendReq(req)
            }
        }
    }
    private fun genPayReq(payInfo: PayInfo) {
        if (req != null) {
            req!!.appId = payInfo.appid
            req!!.partnerId = payInfo.partnerid
            req!!.prepayId = payInfo.prepayid
            req!!.nonceStr = payInfo.noncestr
            req!!.timeStamp = payInfo.timestamp
            req!!.packageValue = payInfo.package_str
            req!!.sign = payInfo.sign
        }
    }
    private fun judgeCanGo(APP_I: String): Boolean {
        getWXAPI(APP_I)
        if (api != null) {
            if (!api!!.isWXAppInstalled()) {
                Toast.makeText(activity, "请先安装微信应用", Toast.LENGTH_SHORT).show()
                return false
            }
        }
        return true
    }
    fun getWXAPI(APP_ID: String?): IWXAPI? {
        if (api == null) {
            //通过WXAPIFactory创建IWAPI实例
            api = WXAPIFactory.createWXAPI(activity, null)
            req = PayReq()
            //将应用的appid注册到微信
            api.registerApp(APP_ID)
        }
        return api
    }



    fun addDataByUrl(url: String) {
//            "https://ntsp.dpca.com.cn/preprod/tmall/#/query/shop" -> {//流量商城

//            " https://ntsp.dpca.com.cn/preprod/app/appMall/appMall.html?" -> {//备件商城

//            "https://ntsp.dpca.com.cn/preprod/tmall/#/active" -> {//活动


        when {
            url.contains("tmall/#/query/shop") -> {
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE90.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            }
            url.contains("app/appMall/appMall.html?") -> {
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE91.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            }
            url.endsWith("tmall/#/active") -> {
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE92.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            }
            url.contains("tmall/#/activeSuccess") -> {
                DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE133.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            }
        }
    }
}